﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HostEditor
{
    public partial class Form1 : Form
    {
        private List<string[]> mylist = new List<string[]>();
        private int selectedRowIndex;
        public Form1()
        {
            InitializeComponent();
            
            dataGridView1.Columns.Add("IP", "IP");
            dataGridView1.Columns.Add("URL", "URL");

            ReadHostsFile();
        }
        
        private void ReadHostsFile()
        {
            string hostsPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
            hostsPath += "\\drivers\\etc\\hosts";

            using (StreamReader sr = new StreamReader(hostsPath))
            {
                string line;

                // 从文件读取并显示行，直到文件的末尾 
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                    if (line.Trim() == string.Empty) continue;
                    if (line.Trim().StartsWith("#")) continue;
                    if (line.Trim().Split(' ').Length != 2) continue;
                    mylist.Add(line.Trim().Split(' '));
                }
            }

            foreach (string[] arr in mylist)
            {
                dataGridView1.Rows.Add(arr);
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                string hostsPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
                hostsPath += "\\drivers\\etc\\hosts";

                using (StreamWriter sw = new StreamWriter(hostsPath))
                {
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        if (row.Cells[0].Value == null || row.Cells[0].Value.ToString() == string.Empty) continue;
                        sw.WriteLine(row.Cells[0].Value.ToString() + " " + row.Cells[1].Value.ToString());
                    }
                }
            }
        }

        private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                selectedRowIndex = e.RowIndex;
            }

            if (e.Button == MouseButtons.Right)
            {
                contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectedRowIndex >= 0)
            {
                dataGridView1.Rows.RemoveAt(selectedRowIndex);
            }
        }
    }
}
